<?php
namespace WeChat;

class wechatClass{
	public function index($appid,$back_url){
		if(empty($appid) || empty($back_url))die('appid或back_url为空!');
        $redirect_uri = urlencode($back_url);
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header("Location:".$url);
        exit;
	}

	public function http_curl($url,$type='get',$res='json',$arr=''){
	    //1.初始化curl
	    $ch = curl_init();
	    //2.设置curl的参数
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    if ($type == 'post') {
	        curl_setopt($ch, CURLOPT_POST, 1);
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
	    }
	    //3.采集
	    $output = curl_exec($ch);
	    //4.关闭
	    curl_close($ch);
	    if ($res == 'json')return json_decode($output,true);
	}

	public function getUserOpentId($code,$appid,$secret){
        //回调地址会传回一个code，则我们根据code去获取openid和授权获取到的access_token
        if(empty($code) || empty($appid) || empty($secret))die('code或appid或secret为空!');
        
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
 
        $res = $this->http_curl($url);
        $access_token = $res['access_token'];
        $getopenid = $res['openid'];
$asaaaaa='';
        //获取用户授权信息
        $urltoc = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$getopenid."&lang=zh_CN";
        $resinfos = $this->http_curl($urltoc);
      
     	return $resinfos;
    }

}

